package com.ganzalang.gmall.threadlocal.common.util;

import org.springframework.beans.SimpleTypeConverter;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @description:
 * @author: Ganzalang
 * @Date 2021/3/26 15:33
 */
public class GlobalParamInfo {

    private static final String USERNAME = "USERNAME";
    private static final String USERID = "USERID";
    private static final String ENCODE = "UTF-8";
    private static final ThreadLocal<Map<String, Object>> GLOBALPARAM = ThreadLocal.withInitial(HashMap::new);

    private GlobalParamInfo() {

    }

    public static String getUsername() {
        Object value = GLOBALPARAM.get().get(USERNAME);
        if (Objects.nonNull(value)) {
            try {
                return URLDecoder.decode(value.toString(), ENCODE);
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        }else {
            return null;
        }
    }

    public static Long getUserId() {
        Object value = GLOBALPARAM.get().get(USERID);
        return Objects.isNull(value) ? null : new SimpleTypeConverter().convertIfNecessary(value, Long.class);
    }

    public static <T> T get(String key, Class<T> clazz) {
        Object value = GLOBALPARAM.get().get(key);
        return Objects.isNull(value) ? null : new SimpleTypeConverter().convertIfNecessary(value, clazz);
    }

    public static void put(String key, Object value) {
        GLOBALPARAM.get().put(key, value);
    }

    public static void clear() {
        GLOBALPARAM.remove();
    }
}
